package com.karry.util;

import com.karry.pojo.User;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;

/*
*
*   他奶奶的，改了一个多星期，终于在2022年3月30日13:49:36改好了，这次为了以防万一，使用中英双语，避免再次出现乱码。
* */
public class MailUtil {

    private Session session;
    private Transport transport;

    public MailUtil(){
        //配置文件
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");

        //创建session
        session = Session.getInstance(properties);
        //开启debug
        session.setDebug(true);
        //获得transport对象
        try {
            transport = session.getTransport();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        //使用邮箱用户名和授权密码连接上邮箱服务器
        //授权密码查看此页面 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
        try {
            transport.connect("smtp.qq.com", "1664793090@qq.com", "QQ邮箱用权限码，没权限码的邮箱用密码");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    private static int getCode(){
        Random r = new Random();

        int code = 100000 + r.nextInt(900000);
        return code;
    }

    public int sendTextEmail(ArrayList<User> users, String text){
        MimeMessage mimeMessage = new MimeMessage(session);

        boolean sF = false, eF = false;

        for (User user : users) {
            if (!user.getEmail().contains("@")){
                //测试所需账号跳过
                continue;
            }
            try {
                //指明邮件发送人
                mimeMessage.setFrom(new InternetAddress("1664793090@qq.com"));
                //指明邮件收件人（此处发给自己）
                mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
                //邮件的标题
                //mimeMessage.setSubject("KarrySong Verification Code");
                mimeMessage.setSubject(MimeUtility.encodeText("KarrySong 官网提示 Tips on the official website", MimeUtility.mimeCharset("GBK"), null));

                //邮件的文本内容
                //mimeMessage.setContent("本次服务的验证码是: " + code +" .请妥善保存，勿要泄露。", "text/html;charset=GBK");

                //mimeMessage.setContent("<p>The verification code of this service is: <span style='color: red;font-size:30px'>" + code + "</span> . Please keep it properly and do not disclose it.</p><p><a href='http://www.karrysong.top/MyBlogWeb' style='font-size:30px'>about more KarrySong</a></p>", "text/html;charset=UTF-8");
                mimeMessage.setContent(new String(("尊敬的" + user.getEmail() + ":<br>"+"<p>" + text + "</p><br><a href='http://www.karrysong.top/MyBlogWeb' style='font-size:30px'>更多关于KarrySong</a>").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), "text/html;charset=GBK");

            } catch (MessagingException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //5、发送邮件
            try {
                transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                //部分成功
                sF = true;
            }catch (Exception e){
                e.printStackTrace();
                //部分失败
                eF = true;
            }
        }
        try {
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        System.out.println(sF + " " + eF);

        if (sF && eF){
            //部分成功部分失败
            return 2;
        }else if (sF){
            //完全成功
            return 1;
        }else {
            //完全失败
            return 0;
        }

    }

    public int send(String mailId){

        MimeMessage mimeMessage = new MimeMessage(session);

        int code = getCode();

        try {
            //指明邮件发送人
            mimeMessage.setFrom(new InternetAddress("1664793090@qq.com"));
            //指明邮件收件人（此处发给自己）
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailId));
            //邮件的标题
            //mimeMessage.setSubject("KarrySong Verification Code");
            mimeMessage.setSubject(MimeUtility.encodeText("KarrySong 验证码 Verification Code", MimeUtility.mimeCharset("GBK"), null));

            //邮件的文本内容
            //mimeMessage.setContent("本次服务的验证码是: " + code +" .请妥善保存，勿要泄露。", "text/html;charset=GBK");

            //mimeMessage.setContent("<p>The verification code of this service is: <span style='color: red;font-size:30px'>" + code + "</span> . Please keep it properly and do not disclose it.</p><p><a href='http://www.karrysong.top/MyBlogWeb' style='font-size:30px'>about more KarrySong</a></p>", "text/html;charset=UTF-8");
            mimeMessage.setContent(new String(("<p>本次服务的验证码是:  <span style='color: red;font-size:30px'>" + code + " </span> <br>请妥善保存，勿要泄露。</p><p><a href='http://www.karrysong.top/MyBlogWeb' style='font-size:30px'>更多关于KarrySong</a></p>" + "<p>The verification code of this service is: <span style='color: red;font-size:30px'>" + code + "</span> <br> Please keep it properly and do not disclose it.</p><p><a href='http://www.karrysong.top/MyBlogWeb' style='font-size:30px'>about more KarrySong</a></p>").getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), "text/html;charset=GBK");

        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //5、发送邮件
        try {
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            return code;
        }catch (Exception e){
            return -1;
        }finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }

    }

    //考虑留一个前端接口，后端批量发送指定信息。

    public static void main(String[] args) {
        new MailUtil().send("1664793090@qq.com");
    }
}
